#Crackle Plugin
import sys,urllib,urllib2,urlparse,json
import xbmcgui, xbmcplugin, xbmcaddon
from BeautifulSoup import BeautifulStoneSoup

base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
try:
    from urlparse import parse_qs
except ImportError:
    #python 2.4 compatibility
    from cgi import parse_qs
    urlparse.parse_qs = parse_qs
args = urlparse.parse_qs(sys.argv[2][1:])

#PLUGIN CONSTANTS
plugin_id = 'plugin.video.crackle'
addon = xbmcaddon.Addon(id=plugin_id)

#COMMON PLUGIN FUNCTIONS
#subfolder url link
def build_url(query):
    return base_url + '?' + urllib.urlencode(query)

#chrome web browser act a like
useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'

def getURL(url):
        print '>>>>>Crackle Plugin :: getURL :: url = '+url
        try:
            req = urllib2.Request(url)
            req.add_header('User-Agent', useragent)
            response = urllib2.urlopen(req)
            link=response.read()
            response.close()
        except urllib2.HTTPError, error:
            print 'Error reason: ', error
            return error.read()
        else:
            return link

mode = args.get('mode', None)
 
if mode is None:
    url = build_url({'mode': 'movies', 'foldername': 'Movies'})
    li = xbmcgui.ListItem('Movies', iconImage='DefaultFolder.png')
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)

    url = build_url({'mode': 'tv', 'foldername': 'TV'})
    li = xbmcgui.ListItem('TV', iconImage='DefaultFolder.png')
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
    
    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'movies':
    popularmoviesurl = 'http://api.crackle.com/Service.svc/popular/movies/full/US/25/?format=json'
    url = build_url({'mode': 'vidlistitems', 'foldername': 'Popular', 'url': popularmoviesurl})
    li = xbmcgui.ListItem('Popular', iconImage='DefaultFolder.png')
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)

    featuredmoviesurl = 'http://api.crackle.com/Service.svc/featured/movies/full/US/25/?format=json'
    url = build_url({'mode': 'vidlistitems', 'foldername': 'Featured', 'url': featuredmoviesurl})
    li = xbmcgui.ListItem('Featured', iconImage='DefaultFolder.png')
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)

    allmoviesurl = 'http://api.crackle.com/Service.svc/browse/movies/full/all/alpha/us?format=json'
    url = build_url({'mode': 'vidlistentries', 'foldername': 'All', 'url': allmoviesurl})
    li = xbmcgui.ListItem('All', iconImage='DefaultFolder.png')
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
    
    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'vidlistitems':
    videoitemsurl = args['url'][0]
    data = getURL(videoitemsurl)
    videolist = json.loads(data)
    for video in videolist['Items']:
        name = video['Title']
        videoid = video['ID']
        thumb = video['ImageUrl2']
        url = build_url({'mode': 'link', 'foldername': name, 'id': videoid})
        li = xbmcgui.ListItem(name, iconImage='DefaultFolder.png', thumbnailImage=thumb)
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)

    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'vidlistentries':
    videoentriesurl = args['url'][0]
    data = getURL(videoentriesurl)
    videolist = json.loads(data)
    for video in videolist['Entries']:
        name = video['Title']
        videoid = video['ID']
        thumb = video['ChannelArtTileLarge']
        url = build_url({'mode': 'link', 'foldername': name, 'id': videoid})
        li = xbmcgui.ListItem(name, iconImage='DefaultFolder.png', thumbnailImage=thumb)
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)

    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'tv':
    alltvurl = 'http://api.crackle.com/Service.svc/browse/shows/full/all/alpha/us?format=json'
    data = getURL(alltvurl)
    videolist = json.loads(data)
    for video in videolist['Entries']:
        name = video['Title']
        videoid = video['ID']
        thumb = video['ChannelArtTileLarge']
        url = build_url({'mode': 'tvepisodes', 'foldername': name, 'id': videoid})
        li = xbmcgui.ListItem(name, iconImage='DefaultFolder.png', thumbnailImage=thumb)
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)

    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'tvepisodes':
    showid = args['id'][0]
    videourl = 'http://api.crackle.com/Service.svc/channel/' + showid + '/folders/US/?format=json'
    data = getURL(videourl)
    showinfo = json.loads(data)
    for show in showinfo['FolderList']:
        for episode in show['PlaylistList'][0]['MediaList']:
            name = episode['Title']
            videoid = episode['ID']
            thumb = episode['Thumbnail_Wide']
            url = build_url({'mode': 'linktv', 'foldername': name, 'id': videoid})
            li = xbmcgui.ListItem(name, iconImage='DefaultFolder.png', thumbnailImage=thumb)
            xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
        
    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'link':
    videoid = args['id'][0]
    name = args['foldername'][0]
    videourl = 'http://api.crackle.com/Service.svc/channel/' + videoid + '/folders/US/?format=json'
    data = getURL(videourl)
    videoinfo = json.loads(data)
    for video in videoinfo['FolderList']:
        medialistid = video['PlaylistList'][0]['MediaList'][0]['ID']
        vidurl = 'http://www.crackle.com/app/vidwall.ashx?flags=-1&fm=' + str(medialistid) + '&partner=20'
        data = getURL(vidurl)
        tree = BeautifulStoneSoup(data, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
        filep = tree.find('i')['p']
        urlfour = 'http://media-us-am.crackle.com/' + filep + '480p_1mbps.mp4'
        li = xbmcgui.ListItem('480p', iconImage='DefaultVideo.png')
        li.setInfo('video', { 'title': name })
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=urlfour, listitem=li)

        urlthree = 'http://media-us-am.crackle.com/' + filep + '360p.mp4'
        li = xbmcgui.ListItem('360p', iconImage='DefaultVideo.png')
        li.setInfo('video', { 'title': name })
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=urlthree, listitem=li)

    xbmcplugin.endOfDirectory(addon_handle)

elif mode[0] == 'linktv':
    medialistid = args['id'][0]
    name = args['foldername'][0]
    vidurl = 'http://www.crackle.com/app/vidwall.ashx?flags=-1&fm=' + str(medialistid) + '&partner=20'
    data = getURL(vidurl)
    tree = BeautifulStoneSoup(data, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
    filep = tree.find('i')['p']
    urlfour = 'http://media-us-am.crackle.com/' + filep + '480p_1mbps.mp4'
    li = xbmcgui.ListItem('480p', iconImage='DefaultVideo.png')
    li.setInfo('video', { 'title': name })
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=urlfour, listitem=li)

    urlthree = 'http://media-us-am.crackle.com/' + filep + '360p.mp4'
    li = xbmcgui.ListItem('360p', iconImage='DefaultVideo.png')
    li.setInfo('video', { 'title': name })
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=urlthree, listitem=li)

    xbmcplugin.endOfDirectory(addon_handle)
